package com.zhiche.lisa.lspm.service.fleet.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.enums.*;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.RegexUtil;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.lspm.dao.mapper.fleet.FleetBindMapper;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierInfo;
import com.zhiche.lisa.lspm.dao.model.driver.Driver;
import com.zhiche.lisa.lspm.dao.model.driver.DriverCarrierBind;
import com.zhiche.lisa.lspm.dao.model.driver.DriverLicense;
import com.zhiche.lisa.lspm.dao.model.fleet.Fleet;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetBind;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetBindLog;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerInfo;
import com.zhiche.lisa.lspm.dto.DriverToErpDTO;
import com.zhiche.lisa.lspm.dto.PersonFleetBindDTO;
import com.zhiche.lisa.lspm.dto.VehicleDTO;
import com.zhiche.lisa.lspm.service.carrier.ICarrierInfoService;
import com.zhiche.lisa.lspm.service.driver.IDriverCarrierBindService;
import com.zhiche.lisa.lspm.service.driver.IDriverLicenseService;
import com.zhiche.lisa.lspm.service.driver.IDriverService;
import com.zhiche.lisa.lspm.service.fleet.IFleetBindLogService;
import com.zhiche.lisa.lspm.service.fleet.IFleetBindService;
import com.zhiche.lisa.lspm.service.fleet.IFleetService;
import com.zhiche.lisa.lspm.service.trailer.TrailerInfoService;
import com.zhiche.lisa.lspm.service.utils.IntegrationUtil;
import com.zhiche.lisa.lspm.service.utils.MdmUtil;
import com.zhiche.lisa.lspm.service.utils.UaaUtil;
import com.zhiche.lisa.lspm.vo.common.AccountVO;
import com.zhiche.lisa.lspm.vo.common.TransportationTypeVO;
import com.zhiche.lisa.lspm.vo.fleet.FleetBindVO;
import com.zhiche.lisa.lspm.vo.fleet.FleetLineVO;
import com.zhiche.lisa.lspm.vo.vehicle.CarrierBasicVO;
import com.zhiche.lisa.lspm.vo.vehicle.TrailerBasicVO;
import com.zhiche.lisa.lspm.vo.vehicle.WeChatVehicle;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 车队与资源绑定关系 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-08-15
 */
@Service
public class FleetBindServiceImpl extends ServiceImpl<FleetBindMapper, FleetBind> implements IFleetBindService {
    private static final Logger LOGGER = LoggerFactory.getLogger(IFleetService.class);
    @Autowired
    private ICarrierInfoService carrierInfoService;
    @Autowired
    private MdmUtil mdmUtil;
    @Autowired
    private IFleetBindLogService iFleetBindLogService;
    @Autowired
    private UaaUtil uaaUtil;
    @Autowired
    private IntegrationUtil integrationUtil;
    @Autowired
    private IDriverLicenseService driverLicenseService;
    @Autowired
    private IFleetBindService fleetBindService;
    @Autowired
    private IFleetService fleetService;
    @Autowired
    private TrailerInfoService trailerInfoService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private IDriverCarrierBindService driverCarrierBindService;

    @Value("${integration.url}")
    private String integrationUrl;

    @Value("${integration.carrierPushErpUrl}")
    private String carrierPushErpUrl;

    @Value("${integration.driverPushErpUrl}")
    private String driverPushErpUrl;

    @Value("${uaa.socketTimeout}")
    private Integer socketTimeout;


    @Value("${integration.trailerPushErpUrl}")
    private String trailerPushErpUrl;

    @Value("${lisa.tms.driverWaybillUrl}")
    private String driverWaybillUrl;

    @Value("${logRedis.isTest}")
    private boolean isTest;

    /**
     * 根据车队信息获取所属承运商下的未绑定车辆
     */
    @Override
    public List<FleetBindVO> queryFleetUnBindLine(FleetBindVO fleetBindVO, String authorization) {
        try {
            JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
            if (Objects.isNull(jwtAccountVO))
                throw new BaseException("获取用户登录信息失败");
            if (Objects.isNull(fleetBindVO.getFleetId())) throw new BaseException("未获取到需要绑定信息的车队");
            if (!Strings.isNullOrEmpty(fleetBindVO.getCarrierPlate()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, fleetBindVO.getCarrierPlate()))
                    throw new BaseException("牵引车车牌字符不合法");
            //获取该用户已使用的车辆

            List<AccountVO> accountVOS = uaaUtil.getListAdminAccountUrl(authorization);
            if (CollectionUtils.isEmpty(accountVOS)) throw new BaseException("未找到登录用户的账号信息");
            List<String> accountIds = Lists.newArrayList();
            for (AccountVO accountVO : accountVOS) {
                accountIds.add(String.valueOf(accountVO.getId()));
            }
            EntityWrapper<FleetBindVO> bindsEw = new EntityWrapper<>();
            bindsEw.in("creator", accountIds).or().eq("fleet_id", fleetBindVO.getFleetId());
            List<FleetBindVO> fleetBindList = baseMapper.queryBindCarrierList(bindsEw);
            EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
            if (Objects.nonNull(fleetBindVO.getCarrierPlate())) {
                ew.like("carrier_plate", fleetBindVO.getCarrierPlate());
            }
            if (Objects.nonNull(fleetBindVO.getDriverMobile())) {
                ew.like("mobile", fleetBindVO.getDriverMobile());
            }
            Fleet fleet = fleetService.selectById(fleetBindVO.getFleetId());
            //绑定剩余的车辆
            if (!CollectionUtils.isEmpty(fleetBindList)) {
                List<Long> carrierIds = Lists.newArrayList();
                fleetBindList.forEach(fleetBindVO1 -> carrierIds.add(fleetBindVO1.getResourceId()));
                ew.notIn("carrier_id", carrierIds);
                ew.eq("tenant_id", fleet.getTenantId());

            }
            return baseMapper.fleetUnBindLine(ew);
        } catch (BaseException e) {
            LOGGER.error("FleetBindServiceImpl.queryFleetUnBindLine" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetBindServiceImpl.queryFleetUnBindLine" + e.getMessage());
            throw new BaseException("获取车辆异常!");
        }
    }

    /**
     * 根据车队信息获取所属承运商下的已绑定车辆
     */
    @Override
    public Page<FleetBindVO> queryFleetBindLine(Page<FleetBindVO> page, String authorization) {
        try {
            if (Objects.isNull(page.getCondition().get("fleetId"))) {
                throw new BaseException("查询失败，未获取到分组信息");
            }
            EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
            ew.eq("fleet_id", page.getCondition().get("fleetId"));
            if(!Objects.isNull(page.getCondition().get("carrierPlate"))){
                ew.like("carrier_plate", (String)page.getCondition().get("carrierPlate"));
            }
            page.setCondition(new HashMap<>());
            List<FleetBindVO> fleetCarrierVOS = baseMapper.fleetBindLine(page, ew);
            page.setRecords(fleetCarrierVOS);
            return page;
        } catch (BaseException e) {
            LOGGER.error("FleetBindServiceImpl.queryFleetBindLine" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetBindServiceImpl.queryFleetBindLine" + e.getMessage());
            throw new BaseException("获取绑定牵引车异常!");
        }
    }

    /**
     * 移入车队
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertFleetBind(Long fleetId, Long resourceId, String authorization) {
        if (Objects.isNull(fleetId)) {
            throw new BaseException("请选择车队");
        }
        EntityWrapper<DriverCarrierBind> ew = new EntityWrapper<>();
        ew.eq("carrier_id",resourceId);
        if (resourceId != null){
            DriverCarrierBind driverCarrierBind = driverCarrierBindService.selectOne(ew);
            if (!Objects.isNull(driverCarrierBind)) {
                List<NameValuePair> pram = Lists.newArrayList();
                pram.add(new BasicNameValuePair("DriverId", driverCarrierBind.getDriverId().toString()));
                String driverWaybill = HttpClientUtil.get(driverWaybillUrl, null, pram, socketTimeout);
                if (!StringUtils.isEmpty(driverWaybill)) {
                    JSONObject driverWaybillJson = JSONObject.parseObject(driverWaybill);
                    if ("false".equals(driverWaybillJson.get("data").toString())) {
                        throw new BaseException("司机还有未完成的运单");
                    }
                }
            }
        }
        WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(resourceId, null);
        if (weChatVehicle != null) {
            trailerInfoService.authTrailerToERP(weChatVehicle.getTrailerId(), authorization);
        }
        //校验车队重复绑定(取消报错,车队层级添加牵引车已经创建了绑定关系)
        EntityWrapper<FleetBind> bdEW = new EntityWrapper<>();
        bdEW.eq("fleet_id", fleetId)
                .eq("resource_id", resourceId)
                .eq("resource_type", TableStatusEnum.STATUS_01.getCode());
        int count = fleetBindService.selectCount(bdEW);
        if (count == 0) {
            //创建新的绑定信息
            FleetBind fleetBind = new FleetBind();
            fleetBind.setFleetId(fleetId);
            fleetBind.setResourceId(resourceId);
            fleetBind.setResourceType(TableStatusEnum.STATUS_01.getCode());
            fleetBind.setGmtCreate(new Date());
            fleetBind.setGmtModify(new Date());
            JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
            if (Objects.nonNull(jwtAccountVO)) {
                fleetBind.setCreator(jwtAccountVO.getAccountId());
            }
            FleetBindLog fleetBindLog = new FleetBindLog();
            BeanUtils.copyProperties(fleetBind, fleetBindLog);
            insert(fleetBind);
            iFleetBindLogService.insert(fleetBindLog);
        }
        // fix  添加运力时 无车队信息 先推送车辆信息到otm / ERP
        carrierToOTM(fleetId, resourceId);
        carrierInfoService.carrierToERP(authorization, resourceId);
        //同时推送司机信息
        driverService.authDriverToERP(authorization, weChatVehicle.getDriverId());
    }

    private void carrierToOTM(Long fleetId, Long resourceId) {
        if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
            //获取中联下面的所有管理员账号
            new Thread(() -> {
                //List<AccountVO> listTenantAccount = uaaUtil.getListTenantAccount(1L, authorization);
                //List<Long> accountIds = new ArrayList<>();
                //for (AccountVO accountVO : listTenantAccount) {
                //    accountIds.add(Long.valueOf(accountVO.getId()));
                //}
//                EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
//                    ew.eq("resource_id", resourceId)
//                            .eq("resource_type", TableStatusEnum.STATUS_01.getCode())
//                            .orderBy("id", false);
//                    List<FleetBindVO> fleetCarrierVOS = fleetBindService.queryBindCarrierList(ew);
//                    VehicleDTO vehicleDTO = new VehicleDTO();
//                    WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(resourceId, null);
//                    if (!CollectionUtils.isEmpty(fleetCarrierVOS)) {
//                        vehicleDTO.setFleetId(fleetId);
//                    } else {
//                        vehicleDTO.setFleetId(weChatVehicle.getLspId());
//                    }
//                    Wrapper<DriverLicense> driverLicenseWrapper = new EntityWrapper<>();
//                    driverLicenseWrapper.eq("driver_id", weChatVehicle.getDriverId());
//                    DriverLicense driverLicense = driverLicenseService.selectOne(driverLicenseWrapper);
//                    if (Objects.nonNull(driverLicense) && !StringUtils.isEmpty(driverLicense.getLicenseId())) {
//                        weChatVehicle.setIdCard(driverLicense.getLicenseId());
//                    }
//                    if (!StringUtils.isEmpty(weChatVehicle.getTrailerTypeId())) {
//                        String trailerTypeName = mdmUtil.getTransportTypeByCode(weChatVehicle.getTrailerTypeId()).getValue();
//                        weChatVehicle.setTrailerTypeName(integrationUtil.getTrailerTypeName(trailerTypeName));
//                        BeanUtils.copyProperties(weChatVehicle, vehicleDTO);
//                        vehicleDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
//                        integrationUtil.exportVehicleToOTM(vehicleDTO);
//                }

               carrierInfoService.carrierAndTrailerToOtm(resourceId,IntegrationEnum.ISACTIVE.getCode());
            }).start();
        }
    }

    @Override
    public List<FleetBind> selectListNoTenant(EntityWrapper<FleetBind> ew) {
        return baseMapper.selectListNoTenant(ew);
    }

    @Override
    public List<FleetBindVO> queryFleetBindNoTenant(EntityWrapper<FleetBindVO> ew) {
        return baseMapper.queryBindCarrierNoTenant(ew);
    }

    /**
     * 只有中联创建的司机的才推送erp
     */
    public void driverToErp(Long carrierId, String authorization) {

        WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(carrierId, null);

        if (Objects.nonNull(weChatVehicle) && Objects.nonNull(weChatVehicle.getNewFleetId())) {
            EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
            ew.eq("resource_id", carrierId)
                    .eq("resource_type", "03")
                    .orderBy("id", false);
            // 得到一条或没有数据
            List<FleetBindVO> bindDriver = fleetBindService.queryBindDriverList(ew);
            if (!CollectionUtils.isEmpty(bindDriver)) {
                Wrapper<FleetLineVO> fleetLineVOWrapper = new EntityWrapper<>();
                fleetLineVOWrapper.eq("id", weChatVehicle.getNewFleetId());
                // 得到一条车队和承运商部分数据
                List<FleetLineVO> fleetLineVOS = fleetService.queryFleetBindList(fleetLineVOWrapper);
                new Thread(() -> {
                    List<AccountVO> listTenantAccount1 = uaaUtil.getListTenantAccount(1L, authorization);
                    for (AccountVO accountVO : listTenantAccount1) {
                        // 创建人存在管理员列表中则进行推送
                        if (fleetLineVOS.get(0).getCreator().equals(accountVO.getId())) {
                            // 设置司机数据并推送到ERP
                            setPushDriverToErpDTODATA(authorization, weChatVehicle, fleetLineVOS);
                        }
                    }
                }).start();
            }
        }
    }

    private void setPushDriverToErpDTODATA(String authorization, WeChatVehicle weChatVehicle,
                                           List<FleetLineVO> fleetLineVOS) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        //推送司机
        DriverToErpDTO driverToErpDTO = new DriverToErpDTO();
        driverToErpDTO.setId(weChatVehicle.getDriverId());
        driverToErpDTO.setDriverName(weChatVehicle.getDriverName());
        driverToErpDTO.setDriverMobile(weChatVehicle.getDriverMobile());
        driverToErpDTO.setFleetName(fleetLineVOS.get(0).getFleetName());
        driverToErpDTO.setFleetId(weChatVehicle.getNewFleetId() + "");
        driverToErpDTO.setLspId(weChatVehicle.getLspId() + "");
        driverToErpDTO.setLspName(weChatVehicle.getLspName());
        driverToErpDTO.setLicenseId(weChatVehicle.getLicenseId());
        if (fleetLineVOS.get(0).getFleetTypeId() == 2) {
            driverToErpDTO.setProperty("3");
        } else if (fleetLineVOS.get(0).getFleetTypeId() == 1) {
            driverToErpDTO.setProperty(fleetLineVOS.get(0).getFleetTypeId().toString());
        } else {
            driverToErpDTO.setProperty("2");
        }
        RedisLogUtil.addSysLogs(SystemEnum.LSPM.getCode(),SystemEnum.INTEGRATION.getCode(),"driver"+driverToErpDTO.getId(), JSON.toJSONString(driverToErpDTO),"/erp-api/driverPushErp",1,1,null,isTest);
        LOGGER.info("driverInfoToErp info url:{},params:{} ", integrationUrl + driverPushErpUrl, JSONObject.toJSONString(driverToErpDTO));
        String driverResult = HttpClientUtil.postJson(integrationUrl + driverPushErpUrl, headNamePairs, JSONObject.toJSONString(driverToErpDTO), socketTimeout);
        LOGGER.info("driverInfoToErp result {} ", driverResult);
    }


    /**
     * 删除司机/牵引车/司机和车队的关联
     */
    @Override
    public void deleteFleetBind(Long id, String resourceType) {
        try {
            EntityWrapper<FleetBind> fleetBindWrapper = new EntityWrapper<>();
            fleetBindWrapper.eq("resource_id", id)
                    .eq("resource_type", resourceType);
            List<FleetBind> FleetBinds = this.selectListNoTenant(fleetBindWrapper);
            if (!CollectionUtils.isEmpty(FleetBinds)) {
                this.delete(fleetBindWrapper);
            }
        } catch (BaseException e) {
            LOGGER.error("FleetBindServiceImpl.DeleteFleetBind" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetBindServiceImpl.DeleteFleetBind" + e.getMessage());
            throw new BaseException("获取绑定牵引车异常!");
        }
    }

    @Override
    public Page<Driver> queryDriverBindWithFleet(Page<Driver> fleetBindsVOPage) {
        try {
            EntityWrapper<Driver> ew = new EntityWrapper<>();
            if (Objects.isNull(fleetBindsVOPage.getCondition().get("fleetId"))) {
                throw new BaseException("请选择车队");
            }
            String fleetId = fleetBindsVOPage.getCondition().get("fleetId").toString();
            ew.eq("lfb.fleet_id", fleetId);
            Page<Driver> page = new Page<>(fleetBindsVOPage.getCurrent(), fleetBindsVOPage.getSize());
            page.setRecords(baseMapper.queryDriverBindWithFleet(page, ew));
            return page;
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("获取绑定司机失败");
        }
    }

    @Override
    public Page<CarrierBasicVO> queryBindCarrierList(Page<CarrierInfo> page) {
        try {
            Page<CarrierBasicVO> carrierBasicVOPage = new Page<>();
            EntityWrapper<CarrierInfo> ew = new EntityWrapper<>();
            if (Objects.isNull(page.getCondition().get("fleetId"))) throw new BaseException("请选择车队");
            String fleetId = page.getCondition().get("fleetId").toString();
            ew.eq("lfb.fleet_id", fleetId);
            List<CarrierInfo> carrierInfos = baseMapper.queryCarrierBindLine(page, ew);
            BeanUtils.copyProperties(page, carrierBasicVOPage);
            List<CarrierBasicVO> carrierBasicVOS = Lists.newArrayList();
            for (CarrierInfo carrierInfo :
                    carrierInfos) {
                CarrierBasicVO carrierBasicVO = new CarrierBasicVO();
                BeanUtils.copyProperties(carrierInfo, carrierBasicVO);
                if (Objects.nonNull(carrierBasicVO.getTractorType())) {
                    if (TractorTypeEnum.TRACTORVEHICLE.getCode().toString().equals(carrierBasicVO.getTractorType()))
                        carrierBasicVO.setTractorTypeName(TractorTypeEnum.TRACTORVEHICLE.getText());
                    if (TractorTypeEnum.RECOVERYVEHICLE.getCode().toString().equals(carrierBasicVO.getTractorType()))
                        carrierBasicVO.setTractorTypeName(TractorTypeEnum.RECOVERYVEHICLE.getText());
                }
                carrierBasicVOS.add(carrierBasicVO);
            }
            carrierBasicVOPage.setRecords(carrierBasicVOS);
            return carrierBasicVOPage;
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("获取绑定牵引车失败");
        }
    }

    @Override
    public Page<TrailerBasicVO> queryBindTrailerWithFleetId(Page<TrailerInfo> page) {
        try {
            Page<TrailerBasicVO> trailerBasicVOPage = new Page<>();
            EntityWrapper<TrailerInfo> ew = new EntityWrapper<>();
            if (Objects.isNull(page.getCondition().get("fleetId"))) {
                throw new BaseException("请选择车队");
            }
            String fleetId = page.getCondition().get("fleetId").toString();
            ew.eq("lfb.fleet_id", fleetId);
            page.setCondition(new HashMap<>());
            List<TrailerInfo> trailerInfos = baseMapper.queryTrailerBindLine(page, ew);
            BeanUtils.copyProperties(page, trailerBasicVOPage);
            List<TrailerBasicVO> trailerBasicVOS = Lists.newArrayList();
            for (TrailerInfo trailerInfo :
                    trailerInfos) {
                TrailerBasicVO trailerInfoLineVO = new TrailerBasicVO();
                BeanUtils.copyProperties(trailerInfo, trailerInfoLineVO);
                if (Objects.nonNull(trailerInfo.getTrailerType())) {
                    List<TransportationTypeVO> allServiceType = mdmUtil.getAllFleetTransportType();
                    String serviceTypeName = trailerInfo.getTrailerType();
                    for (TransportationTypeVO transportationTypeVO :
                            allServiceType) {
                        serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
                    }
                    trailerInfoLineVO.setTrailerTypeName(serviceTypeName);
                }
                trailerBasicVOS.add(trailerInfoLineVO);
            }
            trailerBasicVOPage.setRecords(trailerBasicVOS);
            return trailerBasicVOPage;
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("获取绑定挂车失败");
        }
    }

    /**
     * 匹配对应车队的车辆信息
     *
     * @param ew 条件对象
     */
    @Override
    public List<FleetBindVO> queryBindCarrierList(EntityWrapper<FleetBindVO> ew) {
        return baseMapper.queryBindCarrierList(ew);
    }


    /**
     * ---人送司机绑定车队--
     * 根据车队信息获取所属承运商下的未绑定人送司机
     */
    @Override
    public List<Driver> queryFleetUnBindDriver(FleetBindVO fleetBindVO, String authorization) {
        if (StringUtils.isEmpty(authorization)) {
            throw new BaseException("获取用户登录信息失败");
        }
        if (Objects.isNull(fleetBindVO.getFleetId())) {
            throw new BaseException("车队id不能为空");
        }
        Fleet fleet = fleetService.selectById(fleetBindVO.getFleetId());
        if (fleet != null) {
            Wrapper<Driver> ew = new EntityWrapper<>();
            ew.like("driver_mobile", fleetBindVO.getDriverMobile())
                    .like("service_type", "driver")
                    .eq("lsp_id", fleet.getLspId())
                    .orderBy("driver_id", false);
            return baseMapper.queryPersonUnBindList(ew);
        }
        return null;
    }

    /**
     * 根据车队信息获取所属承运商下的已绑定的人送司机
     */
    @Override
    public Page<FleetBindVO> queryFleetBindDriver(Page<FleetBindVO> page, String authorization) {

        if (page == null) {
            throw new BaseException("page 分页参数不能为空");
        }
        Map<String, Object> condition = page.getCondition();
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        if (Objects.isNull(condition.get("fleetId")) || StringUtils.isEmpty(condition.get("fleetId"))) {
            throw new BaseException("车队id不能为空");
        }
        EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
        ew.eq("fleet_id", condition.get("fleetId").toString())
                .eq("resource_type", FleetResourcesEnum.PEOPLE_SEND_DRIVER.getCode())
                .like("service_type", "drive")
                .orderBy("id", false);
        page.setCondition(new HashMap<>());
        List<FleetBindVO> fleetDriverVOS = baseMapper.queryPersonBindList(page, ew);
        page.setRecords(fleetDriverVOS);
        return page;
    }

    /**
     * 人送司机加入车队
     */
    @Override
    public void insertDriverBindFleet(Long fleetId, Long resourceId, String authorization) {
        if (Objects.isNull(fleetId)) throw new BaseException("请选择车队");
        //校验人送司机是否重复绑定
        EntityWrapper<FleetBind> bdEW = new EntityWrapper<>();
        bdEW.eq("fleet_id", fleetId)
                .eq("resource_id", resourceId);
        int count = fleetBindService.selectCount(bdEW);
        if (count > 0) {
            throw new BaseException("车队id:" + fleetId + "已经绑定" + resourceId + ",请勿重复操作");
        }
        //创建新的绑定信息
        FleetBind fleetBind = new FleetBind();
        fleetBind.setFleetId(fleetId);
        fleetBind.setResourceId(resourceId);
        fleetBind.setResourceType(FleetResourcesEnum.DRIVER.getCode());
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        if (Objects.nonNull(jwtAccountVO)) {
            fleetBind.setCreator(jwtAccountVO.getAccountId());
        }
        FleetBindLog fleetBindLog = new FleetBindLog();
        BeanUtils.copyProperties(fleetBind, fleetBindLog);
        insert(fleetBind);
        iFleetBindLogService.insert(fleetBindLog);
    }

    /**
     * 批量增加人送司机绑定车队
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertPersonBind(PersonFleetBindDTO dto, String authorization) {
        if (dto == null) {
            throw new BaseException("参数不能为空");
        }
        LOGGER.info("FleetBindController.insertPersonBind params : {} ", JSONObject.toJSONString(dto));
        if (CollectionUtils.isEmpty(dto.getResourceIds())) {
            throw new BaseException("请选择需要绑定的司机");
        }
        String fleetId = dto.getFleetId();
        if (StringUtils.isEmpty(fleetId)) {
            throw new BaseException("需要绑定的车队id不能为空");
        }
        for (String resourceId : dto.getResourceIds()) {
            //校验人送司机是否重复绑定
            EntityWrapper<FleetBind> bdEW = new EntityWrapper<>();
            bdEW.eq("fleet_id", fleetId)
                    .eq("resource_id", resourceId)
                    .eq("resource_type", FleetResourcesEnum.PEOPLE_SEND_DRIVER.getCode());
            int count = fleetBindService.selectCount(bdEW);
            if (count > 0) {
                throw new BaseException("已经绑定resourceId:" + resourceId);
            }
            //创建新的绑定信息
            FleetBind fleetBind = new FleetBind();
            fleetBind.setFleetId(Long.valueOf(fleetId));
            fleetBind.setResourceId(Long.valueOf(resourceId));
            fleetBind.setResourceType(FleetResourcesEnum.PEOPLE_SEND_DRIVER.getCode());
            fleetBind.setGmtCreate(new Date());
            fleetBind.setGmtModify(new Date());
            JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
            if (Objects.nonNull(jwtAccountVO)) {
                fleetBind.setCreator(jwtAccountVO.getAccountId());
            }
            FleetBindLog fleetBindLog = new FleetBindLog();
            BeanUtils.copyProperties(fleetBind, fleetBindLog);
            this.insert(fleetBind);
            iFleetBindLogService.insert(fleetBindLog);
            driverService.driverToOtm(Long.valueOf(resourceId));
        }
    }

    /**
     * 取消人送司机绑定
     */
    @Override
    public void removePersonBind(PersonFleetBindDTO dto, String authorization) {
        if (dto == null) {
            throw new BaseException("参数不能为空");
        }
        List<String> resourceIds = dto.getResourceIds();
        String fleetId = dto.getFleetId();
        if (CollectionUtils.isEmpty(resourceIds)) {
            throw new BaseException("请选择需要移除车队的司机");
        }
        if (StringUtils.isEmpty(fleetId)) {
            throw new BaseException("车队id不能为空");
        }

        //删除绑定
        EntityWrapper<FleetBind> fleetBindEW = new EntityWrapper<>();
        fleetBindEW.eq("fleet_id", fleetId)
                .eq("resource_type", FleetResourcesEnum.PEOPLE_SEND_DRIVER.getCode())
                .in("resource_id", resourceIds);
        baseMapper.delete(fleetBindEW);
    }

    @Override
    public List<FleetBindVO> queryBindCarrierNoTenant(EntityWrapper<FleetBindVO> ew) {
        return baseMapper.queryBindCarrierNoTenant(ew);
    }

    @Override
    public List<FleetBindVO> queryBindDriverList(EntityWrapper<FleetBindVO> ew) {
        return baseMapper.queryBindDriverList(ew);
    }

    @Override
    public List<FleetBindVO> queryBindTrailerList(EntityWrapper<FleetBindVO> ew) {
        return baseMapper.queryBindTrailerList(ew);
    }
}



